/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.servlets;


import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.service.services.exports.ExportsService;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.PrintWriter;

import java.util.List;


/**
 * This servlet allows to download a file generated by the Export service.
 *<br>
 * HTTP PARAMETERS :<br>
 * <li>cartname : name of object containing list of entries to process</li>
 * <li>templatename  : export name (application scoped)</li>
 * <li>exportFormat : file format</li>
 *<br>
 * WARNING : do not forget to configure the servlet in web.xml.
 *
 * REMARK : This servlet allows only two export formats (CSV and TXT).
 *  By default, if the exportFormat is not defined the export has the text format.
 * 
 * This class is a specification of the "opiam.admin.faare.struts.servlets.ExportListServlet" class.
 */
public class ExportTempListServlet extends HttpServlet
{
    /** logger de log4j */
    private static Logger _logger =
        Logger.getLogger(ExportTempListServlet.class);

    /** CSV export format. */
    private static final String CSV_FORMAT = "csv";

    /**
    * Servlet processing method.
     * See HttpServlet.doGet
     *
     * @param request HTTP request
     * @param response HTTP response
     *
     * @throws java.io.IOException see HttpServlet
     * @throws javax.servlet.ServletException see HttpServlet
     */
    @Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws java.io.IOException, javax.servlet.ServletException
    {
        String cartname = request.getParameter("cartname");
        String exportName = request.getParameter("exportname");
        String exportFormat = request.getParameter("exportformat");
        String[] elements = request.getParameterValues("eltindex");

        _logger.debug("cartname = " + cartname);
        _logger.debug("exportName = " + exportName);
        _logger.debug("exportFormat = " + exportFormat);

        if ((cartname == null) || cartname.trim().equals(""))
        {
            throw new ServletException(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
        }

        if ((exportName == null) || exportName.trim().equals(""))
        {
            throw new ServletException(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
        }

        try
        {
            // Gets the session
            HttpSession session = request.getSession();

            // Gets the session context
            SessionContext sessionContext = SessionContext.getInstance(session);

            List currentCart = (List) session.getAttribute(cartname);

            if ((exportFormat.toLowerCase()).equals(CSV_FORMAT))
            {
                response.setContentType("application/vnd.ms-excel; charset=iso-8859-1");
                response.setHeader("Content-Disposition",
                                   "attachment;filename=export.csv"
                                  );
            }
            else
            {
                response.setContentType("text/plain; charset=iso-8859-1");
                response.setHeader("Content-Disposition",
                                   "attachment;filename=export.txt"
                                  );
            }

            PrintWriter out = response.getWriter();

            ExportsService.exportMatrix(exportName, currentCart, out,
                                        sessionContext.getUserContext()
                                       );
        }
        catch (Exception se)
        {
            _logger.debug("Error : " + se.toString());
            se.printStackTrace();
        }
    }
}
